import api from '@/store/api';

export interface fan {
  id: string;
  health: string;
  partNumber: number;
  serialNumber: string;
  healthRollup: string;
  identifyLed: string;
  locationNumber: number;
  name: string;
  speed: string;
  statusState: string;
}

export const useFanStore = defineStore('FanStore', () => {
  const fans = ref([] as fan[]);
  const setFanInfo = (data: any[]) => {
    fans.value = data.map((fan: any) => {
      const {
        IndicatorLED,
        Location,
        MemberId,
        Name,
        Reading,
        ReadingUnits,
        Status = {},
        PartNumber,
        SerialNumber,
      } = fan;
      return {
        id: MemberId,
        health: Status.Health,
        partNumber: PartNumber,
        serialNumber: SerialNumber,
        healthRollup: Status.HealthRollup,
        identifyLed: IndicatorLED,
        locationNumber: Location,
        name: Name,
        speed: Reading + ' ' + ReadingUnits,
        statusState: Status.State,
      };
    });
  };
  const getFanInfo = async () => {
    const collection = await api
      .get('/redfish/v1/Chassis')
      .then(({ data: { Members } }) =>
        Members.map((member: { [x: string]: any }) => member['@odata.id']),
      )
      .catch((error) => {
        console.log(error);
      });
    if (!collection) return;
    const fansInfo: any[] = [];
    await api
      .all(
        collection.map((chassis: any) => {
          return api
            .get(`${chassis}/Thermal`)
            .then(({ data: { Fans = [] } }) => {
              fansInfo.push(...Fans);
            });
        }),
      )
      .catch((error) => console.log(error));
    setFanInfo(fansInfo);
  };

  return { fans, setFanInfo, getFanInfo };
});
